package common

import (
	"github.com/ethereum/go-ethereum/common/hexutil"
	"math/big"
	"reflect"
)

// Lengths of hashes and addresses in bytes.
const (
	// HashLength is the expected length of the hash
	HashLength = 32
	// AddressLength is the expected length of the address
	AddressLength = 20
)
var (
	hashT    = reflect.TypeOf(Hash{})
	addressT = reflect.TypeOf(Address{})
)

var EmptyHash = BytesToHash([]byte{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,})

type Hash [HashLength]byte
// SetBytes sets the hash to the value of b.
// If b is larger than len(h), b will be cropped from the left.
func (h *Hash) SetBytes(b []byte) {
	if len(b) > len(h) {
		b = b[len(b)-HashLength:]
	}

	copy(h[HashLength-len(b):], b)
}


func BytesToHash(b []byte )Hash {
	var h Hash
	h.SetBytes(b)

	return h
}

// HexToHash sets byte representation of s to hash.
// If b is larger than len(h), b will be cropped from the left.
//func HexToHash(s string) Hash { return BytesToHash(FromHex(s)) }

// BigToHash sets byte representation of b to hash.
// If b is larger than len(h), b will be cropped from the left.
func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) }

// Bytes gets the byte representation of the underlying hash.
func (h Hash) Bytes() []byte { return h[:] }

// Big converts a hash to a big integer.
func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }


// Hex converts a hash to a hex string.
func (h Hash) Hex() string { return hexutil.Encode(h[:]) }


var EmptyAddress  = BytesToAddress([]byte{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,})

type  Address [AddressLength]byte
func BytesToAddress(b []byte)Address{
	var a Address
	a.SetBytes(b)
	return a
}


/*
当 b 的长度大于a的长度的时候：
因为最小位在最右
*/
func (a *Address)SetBytes(b []byte){
	if len(a) < len(b) {
		b = b[len(b)-AddressLength:]
	}
	copy(a[AddressLength-len(b):],b)
}




